import {
  doDeleteQuestion,
  doGetCommentPage,
  doGetQuestionDetail,
  doPraiseRequest,
} from "../api/apis.ts";
import {Link, useLoaderData, useNavigate} from "react-router-dom";
import {useEffect, useRef, useState} from "react";
import {CommentInfo, CommentPageParam, PageInfo, Question, QuestionInfo} from "../types/commonTypes.ts";
import {Button, Col, Divider, Row, message, Modal, Empty} from "antd";
import {QuestionViewer} from "../views/QuestionViewer.tsx";
import {formatTime} from "../utils/format-utils.ts";
import '../style/hotTag.scss'
import HotTag from "../views/HotTag.tsx";
import PraiseIcon from "../views/icon/PraiseIcon.tsx";
import CommentIcon from "../views/icon/CommentIcon.tsx";
import {useLoginUser} from "../hooks/LoginHooks.tsx";
import CommentList from "../views/CommentList.tsx";

const {confirm} = Modal;

export async function loader({params}: any) {
  const qId = params.questionId;
  if (!qId) {
    throw new Error("questionId is required");
  }
  return qId;
}

export default function () {
  const qid = useLoaderData() as string;
  const userInfo = useLoginUser();
  const [commentPage, setCommentPage] = useState<PageInfo<CommentInfo>>()
  const [detailData, setDetailData] = useState<QuestionInfo>()
  const [praiseState, setPraiseState] = useState<boolean>(false);
  const [praiseCount, setPraiseCount] = useState<number>(0);
  const [commentCount, setCommentCount] = useState<number>(0);
  let clickStatus = false;
  const navigate = useNavigate();
  const getContent = () => {
    return detailData?.detail?.description;
  }
  const doPraise = async () => {
    if (clickStatus) {
      return;
    }

    clickStatus = true;
    const lastState = praiseState;
    setPraiseState(!praiseState);
    setPraiseCount(praiseCount + (praiseState ? -1 : 1));
    try {
      const {code, msg} = await doPraiseRequest(qid, Number(!praiseState))
      if (code != 200) {
        setPraiseState(lastState);
        setPraiseCount(praiseCount + (praiseState ? 1 : -1));
        message.error(msg);
      }
    } catch (e) {
      message.error(e + '');
      setPraiseState(lastState);
      setPraiseCount(praiseCount + (praiseState ? 1 : -1));
    }
    clickStatus = false;
  }
  const doDelete = async () => {
    confirm({
      width: '300px',
      title: '确定删除该问题?',
      onOk: async () => {
        const {code, msg} = await doDeleteQuestion(qid);
        if (code == 200) {
          message.success('删除成功');
          navigate('/')
        } else {
          message.error(msg);
        }
      }
    });
  }
  const getCommentPage = async (pageParam: CommentPageParam) => {
    const {code, data} = await doGetCommentPage(qid, pageParam);
    if (code == 200) {
      setCommentPage(data);
      setCommentCount(Number(data.totalComments));
    }
  }

  const getDetail = async (qid: string) => {
    const {code, data, msg} = await doGetQuestionDetail(qid);
    if (code == 200) {
      setDetailData(data);
      setPraiseState(data.detail?.likeType === 1)
      setPraiseCount(Number(data.detail?.likeCount))
    } else {
      message.error(msg);
    }
  }
  useEffect(() => {
    getDetail(qid);
    getCommentPage({current: 1, size: 5, type: 1})
  }, [qid]);
  const onchangeCommentPage = async (page: number, size: number) => {
    const {code, data} = await doGetCommentPage(qid, {current: page, size: size, type: 1})
    if (code == 200) {
      setCommentPage(data);
      setCommentCount(Number(data.totalComments));
    }
  }
  const commentListRef = useRef<HTMLDivElement>(null);
  const isWidthScreen = document.documentElement.clientWidth > 800;
  return <>
    <div className='detail-main'>

      <Row>
        <Col span={isWidthScreen ? 18 : 24} className='detail-left'>
          {detailData ?
            <>
              <div className='author-info'>
                <h3>{detailData.detail?.title}</h3>
                <div className='create'>
                  <span className='info-item'>阅读: {detailData.detail?.viewCount}</span>
                  <span className='info-item'>喜欢: {detailData.detail?.likeCount} 发布于: </span>
                  <span className='info-item'> {formatTime(Number(detailData.detail?.gmtCreate))}</span>
                </div>
                <div className='tag-list'>
                  {
                    detailData.detail?.tag?.split(',').map((item: string) => (
                      <Link to={`/?tag=${item}`} key={item} className='tag-text'>{item}
                      </Link>
                    ))
                  }
                </div>
              </div>
              <Divider className='divider-detail'/>
              <QuestionViewer content={getContent()}/>
              <Divider className='divider-detail'/>
              <div className='bottom-functions'>
                <div onClick={doPraise}
                     className={'bottom-prize unselectable ' + (praiseState ? 'praised' : 'to-praise')}>
                  <PraiseIcon/>{praiseState ? '已' : ''}赞同 {praiseCount}
                </div>
                <div className='comment-count unselectable' onClick={() => {
                  if (commentListRef.current) {
                    const root = document.getElementById('root');
                    if (typeof root?.scrollTop !== 'undefined') {
                      root.scrollTop = commentListRef.current.offsetTop + 45;
                    }
                  }
                }}>
                  <CommentIcon/>{commentCount}条评论
                </div>
                {userInfo?.id === detailData?.detail?.creator ?
                  <div className='user-functions'>
                    <Button type="primary" onClick={() => {
                      navigate(`/question/edit/${qid}`)
                    }}>
                      编辑
                    </Button>
                    <Button onClick={doDelete} type="primary" style={{marginLeft: '10px'}} danger>
                      删除
                    </Button>
                  </div> : ''}
              </div>
              <div ref={commentListRef}>
                {commentPage ?
                  <CommentList commentPage={commentPage}
                               getCommentPage={getCommentPage}
                               onChangeTotalCommentCount={(count) => {
                                 setCommentCount(Number(count))
                               }}
                               creator={detailData?.detail?.creator || ''}
                               qid={qid}
                               onChangePage={onchangeCommentPage}/>
                  : ''}
              </div>
            </> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE}/>}
        </Col>
          {
              isWidthScreen && <Col span={6}>
                  <div className='author-info'>
                      <h4 className='title-h4'>作者</h4>
                      <div className='author-detail' onClick={() => {
                          navigate(`/?creator=${detailData?.detail?.creator}&creator_name=${detailData?.detail?.creatorName}`)
                      }}>
                          <img className='author-detail__header' src={detailData?.detail?.creatorAvatar} alt=""/>
                          <div className='author-detail__name'>{detailData?.detail?.creatorName}</div>
                      </div>
                  </div>
                  <Divider/>
                  {
                      detailData?.related?.length ? <>
                          <div className='related-questions'>
                              <h4 className={'title-h4'}>相关话题</h4>
                              {
                                  <div className='related-list'>{
                                      detailData?.related?.map((item: Question) =>
                                          <Link to={`/question/index/${item.id}`}
                                                key={item.id}
                                                className='related-item'>
                                              {item.title}
                                          </Link>
                                      )
                                  }
                                  </div>
                              }
                          </div>
                          <Divider className='margin-less'/>
                      </> : ''
                  }

                  <HotTag>
                  </HotTag>
              </Col>
          }
      </Row>
    </div>

  </>
}